package com.quan.sport.gateway.filter;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.quan.common.base.constant.CommonConstant;
import com.quan.common.utils.CommonUtils;
import com.quan.common.utils.IpHelper;
import com.quan.common.utils.JwtTokenUtils;
import com.quan.upms.entity.UpmsLog;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;

/**
 * 访问过滤器
 * 
 * @author yhaoquan
 *
 */
@Component
public class AccessFilter extends ZuulFilter {

	private static Logger logger = LoggerFactory.getLogger(AccessFilter.class);

	@Autowired
	private AmqpTemplate amqpTemplate;
	
	/**
	 * JwtToken秘钥
	 */
	@Value("${jwt.secret:123456}")
	private String jwtSecret;
	
	
	@Override
	public boolean shouldFilter() {
		return true; // 是否执行该过滤器，此处为true，说明需要过滤
	}

	@Override
	public int filterOrder() {
		return 1; // filter执行顺序，通过数字指定 ,优先级为0，数字越大，优先级越低
	}

	@Override
	public String filterType() {
		return "pre"; // 可以在请求被路由之前调用
	}

	@Override
	public Object run() throws ZuulException {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String token = request.getHeader("Auth-Token");

		String requestParams = "无";
		String account = "未知";
		String ip = IpHelper.getIpAddr(request);
		if (request.getMethod().toUpperCase().equals("POST")) {
			requestParams = CommonUtils.readJsonParameter(request) ;
		}
		if (request.getMethod().toUpperCase().equals("GET")) {
			if(StringUtils.isNotBlank(request.getQueryString())) {
				requestParams = request.getQueryString() ;
			}
		}
		
		if(StringUtils.isNotBlank(token) && !"undefined".equals(token)) {
			Jws<Claims> claims = JwtTokenUtils.parse(token, jwtSecret) ;
			Claims body = claims.getBody() ;
			account = (String) body.get("account");
		}

		UpmsLog log = new UpmsLog() ;	
		log.setName("访问日志");
		log.setType("访问日志");
		log.setRequestUri(request.getRequestURI());
		log.setRequestMethod(request.getMethod());
		log.setRequestParams(requestParams);
		log.setLoginUser(account);
		log.setIp(ip);
		
		this.amqpTemplate.convertAndSend(CommonConstant.EXCHANGE_TOPIC, CommonConstant.MQ_TOPIC_MESSAGE_DEFAULT, log);

		logger.info("{} {} {}", request.getMethod(), request.getRequestURL().toString(), requestParams);
		return null;
	}
	

}
